package com.esun.service.mq.listener;

import com.alibaba.fastjson.JSONObject;
import com.esun.api.request.MongoSyncRequestDto;
import com.esun.common.constant.SystemsConstant;
import com.esun.common.exception.CustomException;
import com.esun.dao.das.BaseDas;
import com.esun.dao.eo.BaseEo;
import com.esun.service.mq.enums.BaseEoEnum;
import com.esun.service.mq.enums.DasEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Optional;


/**
 * @author John.xiao
 * @date 2021/9/1 13:29
 */
@Slf4j
@Service
public class SyncListener {

	BaseDas baseDas;

	@StreamListener("input")
	public void receiveSync(String msg){
		MongoSyncRequestDto requestDto = JSONObject.parseObject(msg,MongoSyncRequestDto.class);
		if (requestDto == null){
			throw new CustomException(msg+"消息格式错误");
		}
		BaseEoEnum baseEoEnum = BaseEoEnum.match(requestDto.getCollection());
		DasEnum dasEnum = DasEnum.match(requestDto.getCollection());
		log.debug(msg);
		if (baseEoEnum == null ||  dasEnum == null){
			throw new CustomException(msg+"未找到相应的集合（表）,请检查参数是否正确");
		}
		baseDas = dasEnum.getDas();
		setDatabase(requestDto.getDatabase());
		List entityList = JSONObject.parseArray(requestDto.getEntityJson(),baseEoEnum.getEntity().getClass());
		invoke(requestDto.getRequestMethod(),entityList);
	}

	private void setDatabase(String database){
		if (StringUtils.isBlank(database)){
			baseDas.setDbname(SystemsConstant.DEFAULT_DATABASE);
		}
		else {
			baseDas.setDbname(database);
		}
	}
	private void invoke(String method,List<BaseEo> entityList){
		switch (method){
			case "insert":
				invokeInsert(entityList);
				break;
			case "update":
				invokeUpdate(entityList);
				break;
			case "delete":
				invokeDelete(entityList);
				break;
			default:
				throw new CustomException(method+"未找到相应的方法，请检查参数是否正确");
		}
	}

	private void invokeInsert(List<BaseEo> entityList){
		baseDas.insertBatch(entityList);
	}

	private void invokeUpdate(List<BaseEo>  entityList){
		entityList.forEach((entity) -> {
			BaseEo queryEntity = new BaseEo();
			queryEntity.setId(entity.getId());
			queryEntity.setGuid(entity.getGuid());
			baseDas.update(queryEntity,entity);
		});
	}

	private void invokeDelete(List<BaseEo>  entityList){
		entityList.forEach((entity) -> {
			baseDas.delete(entity);
		});
	}


}

